package com.ccteam.shared.domain.playlistsheet.music

import com.ccteam.model.Resource
import com.ccteam.model.music.MusicVO
import com.ccteam.network.ApiError
import com.ccteam.shared.data.playlistsheet.PlaylistSheetRepository
import com.ccteam.shared.domain.FlowUseCase
import com.ccteam.shared.result.playlistsheet.AddMediaItem
import com.ccteam.shared.utils.EMPTY_STRING
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/17
 *
 * 获取当前歌单的歌曲列表Domain层
 */
class AddOnlineMusicPlaylistMusicDataUseCase @Inject constructor(
    private val playlistSheetRepository: PlaylistSheetRepository
): FlowUseCase<String, List<AddMediaItem>>(
    Dispatchers.IO
) {
    override fun execute(parameters: String): Flow<Resource<List<AddMediaItem>>> {
        return playlistSheetRepository.getPlaylistMusicList(parameters).map {
            when(it){
                is Resource.Success ->
                    Resource.Success(transformToAddMediaItemList(it.data?.data))
                is Resource.Loading ->
                    Resource.Loading(transformToAddMediaItemList(it.data?.data))
                is Resource.Error ->
                    Resource.Error(ApiError.serverErrorCode,it.message ?: "未知错误",transformToAddMediaItemList(it.data?.data))
            }
        }
    }

    private fun transformToAddMediaItemList(musicVOList: List<MusicVO>?): List<AddMediaItem>{
        return musicVOList?.map {
            AddMediaItem(it.id,it.name,it.artists,it.imgUrl ?: EMPTY_STRING,false)
        } ?: emptyList()
    }
}